<template>
  <div class="box_container">
    <el-card class="pag-container">
      <div class="title_font">
        <span class="_before">基本信息</span>
      </div>
      <el-form :model="companyForm" label-width="50px" label-position="left" style="margin-top: 40px;width: 800px;">
        <el-form-item>
          公司名称：{{ companyForm.name }}
          <a style="color: #7CAFFF;margin-left: 10px"
            @click="realAuthentication">&nbsp;&nbsp;&nbsp;修改企业名称</a>
        </el-form-item>
        <el-form-item>
          统一社会信用代码： {{ companyForm.invoiceTaxnum || '空' }}
        </el-form-item>
        <el-form-item>主营业务：
          <!-- 主营业务： {{ filter.mainBusiness[companyForm.mainBusiness] }} -->
          <el-select v-model="companyForm.mainBusiness" multiple placeholder="请选择" style="width: 150px;">
            <el-option v-for="item in param.mainBusiness"  :value="{ value: item.value, label: item.label}" :key="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          认证完成时间： {{ formatDate(companyForm.createTime, 2) }}
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;">企业LOGO:</div>
          <upload-Img ref="uploadImgRef" v-model="param.mainImgList" :maxLimit="1" :urlList="companyForm.companyLogo"
            @uploadSccess="logoInfo" style="width:1000px;height: 1000px;" />
          <div style="width: 100%;font-size: small;font-weight: 500;">图片大小不能超过1M，支持png/jpg格式，尺寸500*500px</div>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;">企业宣传活动:</div>
          <upload-Img ref="uploadImgRef" v-model="param.mainImgList" :urlList="companyForm.publicizePhoto"
            @uploadSccess="publicizePhotoInfo" style="width:1000px;height: 1000px;" />
          <div style="width: 100%;font-size: small;font-weight: 500;">图片大小不能超过2M，支持png/jpg格式，尺寸1120*630px</div>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;">发货印章:</div>
          <upload-Img ref="uploadImgRef" v-model="param.mainImgList" :maxLimit="1" :urlList="companyForm.shippingSignet"
            @uploadSccess="shippingSignetInfo" style="width:1000px;height: 1000px;" />
          <div style="width: 100%;font-size: small;font-weight: 500;">图片大小不能超过1M，支持png/jpg格式，尺寸500*500px</div>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%;">产品与服务:</div>
          <el-button @click="addService">
            <el-icon>
              <Plus />
            </el-icon>
            新增产品/服务
          </el-button>
        </el-form-item>
        <el-form-item>
          <div v-for="(item, index) in picInfo.businessList" :key="index" style="margin-left: 10px;">
            <div>{{ item.title }}</div>
            <div style="width: 100px;height: 100px;border: 1px solid #ccc;overflow: hidden;">
              <img :src="item.url" alt="" style="width: 100%;">
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div>企业介绍:</div>
          <el-input v-model="companyForm.publicizeIntroduce" type="textarea" rows="3" show-word-limit maxlength="200"
            placeholder="请输入企业介绍/企业文化/发展历程" />
        </el-form-item>
      </el-form>
      <!-- <div style="width: 100%;text-align: center;">
        <el-button type="primary" @click="handleUpdate">保存1</el-button>
      </div> -->
    </el-card>

    <el-card class="pag-container">
      <div class="title_font">
        <span class="_before">银行账户</span>
      </div>
      <el-form :model="from" inline label-width="180px">
        <el-form-item label="银行名称:" prop="bank" :rules="from.rules.bank">
          <el-input v-model="from.bank" placeholder="开户行名称" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="RMB账户：" prop="rmbAccount" :rules="from.rules.bank">
          <el-input v-model="from.rmbAccount" placeholder="请输入RMB账户" style="width: 300px;" />
        </el-form-item>
        <br>
        <el-form-item label="SWIFT CODE：" prop="swiftCode" :rules="from.rules.bank">
          <el-input v-model="from.swiftCode" placeholder="请输入SWFT CODE" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="USD账户：" prop="usdAccount" :rules="from.rules.bank">
          <el-input v-model="from.usdAccount" placeholder="请输入USD账户" style="width: 300px;" />
        </el-form-item>
      </el-form>
      <!-- <div style="width: 100%;text-align: center;">
        <el-button type="primary">保存2</el-button>
      </div> -->
    </el-card>

    <el-card class="pag-container">
      <div class="title_font">
        <span class="_before">联系方式</span>
      </div>
      <el-form :model="from" inline label-width="120px">
        <el-form-item label="联系人:" prop="contacts" :rules="from.rules.contacts">
          <el-input v-model="from.contacts" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="所在地:" prop="location" :rules="from.rules.location">
          <el-input v-model="from.location" style="width: 300px;" />
        </el-form-item>
        <br>
        <el-form-item label="联系电话:" prop="tel" :rules="from.rules.tel">
          <el-input v-model="from.tel" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="详细地址:" prop="detailedAddress" :rules="from.rules.detailedAddress">
          <el-input v-model="from.detailedAddress" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="邮箱地址:" prop="email" :rules="from.rules.email">
          <el-input v-model="from.email" style="width: 300px;" />
        </el-form-item>
      </el-form>
      <div style="width: 100%;text-align: center;">
        <el-button type="primary" @click="handleUpdate">保存</el-button>
      </div>
    </el-card>

    <el-card class="pag-container">
      <div class="title_font">
        <span class="_before">企业认证</span>
      </div>
      <el-row>
        <div v-for="(item, index) in companyForm.companyImgs" :key="index" style="margin-left: 20px;float: left;">
          <div>{{ item.lable }}</div>
          <div style="width: 200px;border: 1px solid #ccc;position: relative;">
            <img :src="item.value" v-if="item.value" style="width: 100%;margin-bottom:-5px" />
            <!-- <el-icon style="position:absolute;left:50%;top:30px"><ZoomIn /></el-icon> -->
            <el-button type="primary" style="position:absolute;right:0;bottom:-2px;height:25px;font-size:12px"  @click="toPreview(item)">点击预览</el-button>
          </div>
        </div>
      </el-row>
      <div style="width: 100%;text-align: center;margin-top: 30px;">
        <el-button v-if="from.examineStatus=='10'" @click="goCompanyCheck" type="primary">企业签署核验</el-button>
      </div>
    </el-card>

   <el-dialog v-model="from.dialogVis" title="" width="800" align-center >
      <img :src="from.imgUrl" alt="" style="width:100%;">
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="from.dialogVis = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="picInfo.isaddServiceShow" title="新增产品/服务" width="500">
      <el-form :model="picInfo">
        <el-form-item label="标题：">
          <el-input v-model="picInfo.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="详情图:">
          <upload-Img ref="uploadImgRef" v-model="picInfo.imgList" :maxLimit="1" :urlList="picInfo.imgList"
            @uploadSccess="productIntrophto" style="width:1000px;height: 1000px;" />
        </el-form-item>
        <p style="text-align: center;font-size: 12px;color: #ccc;">详情图只能添加一张</p>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="picInfo.isaddServiceShow = false">取消</el-button>
          <el-button type="primary" @click="picInfo.isaddServiceShow = false">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-card class="pag-container">
      <div class="title_font">
        <span style="background-color: #2158F3;"> &nbsp</span> &nbsp;认证记录
      </div>
      <ul>
        <li><span>认证类型</span> <span>认证内容</span>
          <span>驳回原因</span><span>当前状态</span><span>创建日期</span><span>审核日期</span><span>操作</span>
        </li>
        <li v-for="(item, index) in tableData.dataInfo" :key="index">
          <span>
            <template v-if="item.authenticationType == '5'">企业认证</template>
            <template v-else-if="item.authenticationType == '10'">管理员认证</template>
            <template v-else>--</template>
          </span> <!--认证类型 -->
          <span>
            <template v-if="item.authenticationFlag == '5'">企业信息实名认证</template>
            <template v-else-if="item.authenticationFlag == '10'">管理员账号实名认证</template>
            <template v-else> -- </template>
          </span><!--认证内容 -->
          <span>
            <template v-if="item.reasonRejection"> {{ item.reasonRejection }}</template>
            <template v-else>--</template>

          </span><!--驳回原因 -->
          <span>
            <template v-if="item.status == '5'"><em style="color:#9d9d3e;">待审核</em></template>
            <template v-else-if="item.status == '10'"><em style="color: green;">已通过</em></template>
            <template v-else-if="item.status == '15'"><em style="color: red;">已驳回</em></template>
            <template v-else>--</template>
          </span><!--当前状态 -->
          <span>{{ item.createTime?.substring(0, 10) }}</span><!--创建日期 -->
          <span>{{ item.updateTime?.substring(0, 10) }}</span><!--审核日期 -->
          <span>
            <!-- <el-icon style="margin-right: 30px;">
              <Search />
            </el-icon> -->
            <el-icon v-if="item.status == '15'">
              <router-link to="/enterpriseManage/realAuthentication">
                <RefreshRight />
              </router-link>
            </el-icon>
            <el-icon v-if="item.status == '5'">
              <Top />
            </el-icon>
          </span>
        </li>
      </ul>
    </el-card>
    <el-dialog v-model="param.dialogVisibleWarning" @close="param.step = 1" title="认证变更" style=" text-align: center;">
      <div v-if="param.step == 1">
        <div>
          <span>企业名称变更需提交变更后的企业营业执照</span>
          <div>
            <el-checkbox v-model="param.isAgree" />
            <span style="font-size: 12px;">
              我已阅读并接受
              <a href="#">《申请账号主体变更协议》</a>
              <a href="#">《接受账号主体变更协议》</a>
            </span>
          </div>
        </div>
        <el-button type="primary" @click="param.step = 2">下一步</el-button>
      </div>
      <div v-if="param.step == 2">
        <el-form label-width="200">
          <el-form-item label="原企业名称：">{{ companyForm.name }}</el-form-item>
          <el-form-item label="变更后企业名称：">
            <el-input v-model="param.companyNameNew" size="large" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="变更后企业营业执照：">
            <licenseOcr ref="licenseRef" :needOcr="true" :drag="false" @ocrLicense="ocrLicense">
            </licenseOcr>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="param.step = 1">上一步</el-button>
        <el-button type="primary" @click="param.dialogVisibleWarning = false">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="param.dialogEVisibleWarning" @closed="handleCloseEQianBao" title="" style="width: auto;">
      <iframe :src="param.longContractUrl" width="100%" height="800px" frameborder="0"></iframe>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import IDCardOcr from '@/components/upload/IDCardOcr.vue'
import licenseOcr from '@/components/upload/licenseOcr.vue'
import orderInfo from '@/store/modules/order'
import { formatDate } from '@/utils'
import { ref, reactive, toRefs, onMounted, onActivated } from 'vue'
import { getSysCompanyInfoById, eSignAuth, authInfoList } from '@/api/company/index'
import uploadImg from '@/components/upload/img.vue'
import { getReturnData } from '../../../api/orderManage/returnBoxDetail'
import { ElMessage } from 'element-plus'
const from = reactive({
  examineStatus:'10',//是否实名
  dialogVis:false,
  imgUrl:'',
  contacts:'',
  location:'',
  tel:'',  
  detailedAddress:'',
  email:'',
  bank:'',
  rmbAccount:'',
  usdAccount:'',
  swiftCode:'',
  rules: {
    bank:[
      { required: true, message: '不能为空', trigger: 'blur' },
      { min: 4, max: 32, message: '长度在4到32个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 8, max: 16, message: '长度在8到16个字符', trigger: 'blur' },
      { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$/, message: '密码必须包含大小写字母、数字和特殊字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    tel: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    contacts: [
      { required: true, message: '请输入联系人', trigger: 'blur' },
      { min: 3, max: 32, message: '长度在3到32个字符', trigger: 'blur' }
    ],
    location:[
      { required: true, message: '请输所在地', trigger: 'blur' },
      { min: 10, max: 50, message: '长度在10到50个字符', trigger: 'blur' }
    ],
    detailedAddress:[
      { required: true, message: '请输详细地址', trigger: 'blur' },
      { min: 10, max: 100, message: '长度在10到100个字符', trigger: 'blur' }
    ]
  }
})

const toPreview = (row) =>{
  from.imgUrl = row.value
  from.dialogVis = true
  // console.log(row)

}

const param = reactive({
  step: 1,
  mainImgList: [],
  showMainImgList: [],
  mainBusiness: [
    { value: 5, label: '租箱企业' },
    { value: 10, label: '集装箱公司' },
    { value: 15, label: '集卡公司' },
    { value: 20, label: '堆场公司' },
  ],
  dialogEVisibleWarning: false,
  longContractUrl: ''
})
const companyForm = ref({
  name: '',
  businessList: [], //'1.核心业务:', '2.产品介绍:', '3.解决方案:', '4.客户案例:',
  companyImgs: [{ lable: '营业执照：', value: '' }, { lable: '法人身份证：', value: '' },]
})
const filter = reactive({
  mainBusiness: { '5': '货代企业', '10': '租箱企业', '15': '箱贸易企业', '20': '集卡车队企业', '25': '堆场企业' }
})
const picInfo = reactive({ //暂存提交图片信息
  companyLogo: [],
  publicizePhoto: [],
  shippingSignet:[],
  imgList: [],
  title: '',
  businessList: [],
  // productPhoto:[],
  isaddServiceShow: false,
  name: ''

})
const productIntrophto = (row) => {
  const newRow = Object.assign(row, { title: picInfo.title })
  // localStorage.setItem('imgList', JSON.stringify(newRow))
  // const imgList = localStorage.getItem(imgList)
  picInfo.businessList.push(newRow)

}

const logoInfo = (row) => {
  // console.log('row:', row)
  picInfo.companyLogo.push(row)
  // file 是当前上传的文件对象，fileList 是所有已上传的文件列表
}
const publicizePhotoInfo = (row) => {
  picInfo.publicizePhoto.push(row)
}
const shippingSignetInfo = (row) => {
  picInfo.shippingSignet.push(row)
}
onActivated(() => {
  getCompanyInfo()
  getAuthInfoList()
  from.examineStatus = userStore.getUser().examineStatus
  console.log('user',userStore.getUser())
})

const tableData = reactive({ // 认证记录表格数据
  dataInfo: [],
  recordedInfo: {},
  recordedInfoDialog: false
})

// 获取用户信息
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const user = userStore.getUser()
const getCompanyInfo = () => {
  const companyId = user.companyId
  getReturnData
  if (!companyId) return
  getSysCompanyInfoById(companyId).then(res => {
    console.log('res', res)
    companyForm.value = res.data
    from.contacts = res.data.contacts
    from.location = res.data.location
    from.tel = res.data.tel
    from.detailedAddress = res.data.detailedAddress
    from.email = res.data.email
    from.bank = res.data.bank
    from.rmbAccount = res.data.rmbAccount
    from.usdAccount = res.data.usdAccount
    from.swiftCode = res.data.swiftCode
    companyForm.value.businessList = [{ lable: '1.核心业务:', value: '' }, { lable: '2.产品介绍:', value: '' },]
    picInfo.businessList = JSON.parse(res.data.productPhoto) || []
    companyForm.value.companyLogo = JSON.parse(res.data.companyLogo)
    companyForm.value.publicizePhoto = JSON.parse(res.data.publicizePhoto)
    companyForm.value.shippingSignet = JSON.parse(res.data.shippingSignet)
    companyForm.value.publicizeIntroduce = res.data.publicizeIntroduce
    // companyForm.value.mainBusiness = res.data.mainBusiness
    let mainBusinessList=JSON.parse(res.data.mainBusiness)
    let mainBusinessListFor=[]
   mainBusinessList.forEach((item)=>{
      let obj={
        value:item.id,
        label: item.name,
      }
      mainBusinessListFor.push(obj)
    })
    companyForm.value.mainBusiness=mainBusinessListFor

    const businessLicense = JSON.parse(res.data.businessLicense) || []
    const identityPhoto = JSON.parse(res.data.identityPhoto)
    if (businessLicense.length > 0 && businessLicense[0].url) {
      companyForm.value.companyImgs = [
        { lable: '营业执照：', value: businessLicense[0].url },
        { lable: '法人身份证 正：', value: identityPhoto[0].url},
        { lable: '法人身份证 反：', value: identityPhoto[1].url }
      ]
    }
  })
}

//企业实名认证
import { useRouter } from 'vue-router';
const router = useRouter()

const goCompanyCheck = () => {
  const data = {
    companyName: companyForm.value.name,
    psnName: user.nickname
  }
  // const data = {
  //   companyName: '河南陆海国际智能科技有限公司PAAZ',
  //   psnName: '舒广亮'
  // }
  eSignAuth(JSON.stringify(data)).then(res => {
    console.log(res)
    if (res.data.authUrl) {
      param.longContractUrl = res.data.authUrl
      param.dialogEVisibleWarning = true
    }
  })
  // router.push('companyCheck')
}

// 发票识别
const ocrLicense = (val: any) => {
  // console.log(val.name)
  param.companyNameNew = val.name
  return invoice.value.invoiceNo = val.data.invoiceNo
}
//修改实名认证
const realAuthentication=()=>{
  router.push({
    path: '/enterpriseManage/realAuthentication',
    query: {
      type:2,
      id:companyForm.value.id,
      name:companyForm.value.name,
    }
  })
}

// 公司信息变更
import { addSysCompany, updateSysCompany } from '@/api/company/index'
import { Console } from 'console'
import { name } from 'echarts-extension-amap'
import { fr } from 'element-plus/es/locale/index.mjs'
function handleUpdate() {
  let companyL = picInfo.companyLogo;
  if (companyL.length == 0) {
    companyL = companyForm.value.companyLogo
  }
  let publicizeP = picInfo.publicizePhoto
  if (publicizeP.length == 0) {
    publicizeP = companyForm.value.publicizePhoto
  }
  let shippingSignetP = picInfo.shippingSignet
  if (shippingSignetP.length == 0) {
    shippingSignetP = companyForm.value.shippingSignet
  }
  let mainBusinessList=[]
   companyForm.value.mainBusiness.forEach((item)=>{
      let obj={
        id:item.value,
        name: item.label,
      }
      mainBusinessList.push(obj)
    })
  
  const data = {
    id: companyForm.value.id,
    name: companyForm.value.name,
    companyLogo: JSON.stringify(companyL), //企业logo
    publicizePhoto: JSON.stringify(publicizeP),//企业宣传活动图
    shippingSignet: JSON.stringify(shippingSignetP),//企业宣传活动图

    // businessLicense: [   //营业执照
    //   // {
    //   //   name: "20240712/324ec5ab3da2443b934eb9bc596990d1.jpg",
    //   //   originalFileName: "原图sync.jpg",
    //   //   url: "http://47.122.3.254:9000/default/20240712/324ec5ab3da2443b934eb9bc596990d1.jpg"
    //   // }
    // ],
    // identityPhoto: [
    //   {
    //     name: "20240712/324ec5ab3da2443b934eb9bc596990d1.jpg",
    //     originalFileName: "原图sync.jpg",
    //     url: "http://47.122.3.254:9000/default/20240712/324ec5ab3da2443b934eb9bc596990d1.jpg",
    //     type: 1
    //   },
    //   {
    //     name: "20240712/324ec5ab3da2443b934eb9bc596990d1.jpg",
    //     originalFileName: "原图sync.jpg",
    //     url: "http://47.122.3.254:9000/default/20240712/324ec5ab3da2443b934eb9bc596990d1.jpg",
    //     type: 2
    //   }
    // ],
    productPhoto: JSON.stringify(picInfo.businessList),
    // productPhoto: [
    //   {
    //     name: "20240712/324ec5ab3da2443b934eb9bc596990d1.jpg",
    //     originalFileName: "原图sync.jpg",
    //     url: "http://47.122.3.254:9000/default/20240712/324ec5ab3da2443b934eb9bc596990d1.jpg"
    //   }
    // ],
    publicizeIntroduce: companyForm.value.publicizeIntroduce,
    bank: from.bank,
    rmbAccount: from.rmbAccount,
    usdAccount: from.usdAccount,
    swiftCode: from.swiftCode,
    email: from.email,
    contacts: from.contacts,
    tel: from.tel,
    location: from.location,
    detailedAddress: from.detailedAddress,
    mainBusiness:JSON.stringify(mainBusinessList)
    
  }
  console.log("data:", data)
  updateSysCompany(JSON.stringify(data)).then(res => {
    console.log('res:', res)
    ElMessage.success('保存成功')
    getCompanyInfo()
  })
}

const getAuthInfoList = () => {
  const dataInfo = {
    companyId: companyForm.value.id,
    pageNum: 1,
    pageSize: 10

  }
  authInfoList(JSON.stringify(dataInfo)).then(res => {
    // console.log(res)
    tableData.dataInfo = res.data

  })
  // authInfoList({
  //   pageNum: 1,
  //   pageSize: 10,
  //   companyId: companyId
  // }).then((res) => {

  // })
}
// 新增产品服务
const addService = () => {
  if (picInfo.businessList.length >= 6) return ElMessage.warning('最多上传6张图片')
  picInfo.isaddServiceShow = true

}
</script>
<style scoped>
.title_font {
  font-weight: bold;
  font-size: 14px;
  margin: 10px 0 10px 0;
}

.pag-container {
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
  color: #606266;
  font-family: 'Source Han Sans CN';
  font-weight: 600;
}

.box_container {
  box-sizing: border-box;
  padding: 10px;
}

ul {
  list-style: none;
  font-weight: 500;
  font-size: 14px;
  width: 1400px;
}

ul li {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #eaecf1;
}

ul li:first-child {
  background-color: #eaecf1;
  height: 40px;
  line-height: 40px;
  font-weight: 600;
  font-size: 16px;
}

ul li span {
  width: 180px;
  display: inline-block;
  text-align: center;
}
</style>